package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class CheckItemIServicempl implements CheckItemService {
    @Autowired
    private CheckItemMapper checkItemMapper;

    @Autowired
    private CheckGroupMapper checkGroupMapper;


    /**
     * 新增检查项
     * @param checkItem
     * @return
     */
@Transactional
    public void add(CheckItem checkItem) {
        checkItemMapper.insert(checkItem);
    }




    /**
     * 编辑检查项
     * @param checkItem
     * @return
     */
    public void edit(CheckItem checkItem) {

        checkItemMapper.update(checkItem);
    }

    /**
     * 根据code和name分页查询检查项
     */
    public PageResult page(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<CheckItem> page = checkItemMapper.selectByCondition(queryPageBean);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 删除检查项
     * @param id
     * @return
     */
    @Transactional
    public void delete(Integer id) {
        List<Long> count = checkGroupMapper.findCheckGroupIdByCheckItemId(id);
        if (count != null && count.size()>0){
            throw new RuntimeException(MessageConstant.DELETE_CHECKITEM_FAIL);
        }else {
            checkItemMapper.deleteById(id);
        }
    }

    /**
     * 根据id查询检查项
     */
    public CheckItem findById(Integer id) {
        CheckItem checkItem = checkItemMapper.findById(id);
        return checkItem;
    }

    @Override
    public List<CheckItem> findAll() {
        List<CheckItem> checkItems = checkItemMapper.selectall();
        return checkItems;
    }

    @Override
    public List<CheckItem> findCheckItemById(Integer groupId) {
        List<CheckItem> checkItems = checkItemMapper.findCheckItemById(groupId);
        return checkItems;
    }

}
